//
//  OrderViewController.m
//  AmazingShopping
//
//  Created by Tan on 5/26/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "OrderViewController.h"

@interface OrderViewController ()

@end

@implementation OrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"Order";
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(didFinishOrder)];
    self.navigationItem.rightBarButtonItem = doneButton;
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.tableView addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self isTextFilled];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTableView:nil];
    [super viewDidUnload];
}

- (void)didFinishOrder{
    [self hideKeyboard];
    [self.view setAlpha:0.5];
    [self.view setUserInteractionEnabled:NO];
    UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 10, 10)];
    [loading setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:loading];
    [loading startAnimating];
    
    //Send order information to server
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/order", serverPath]];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
    [request addPostValue:fullNameTextField.text forKey:@"fullname"];
    [request addPostValue:streetTextField.text forKey:@"street"];
    [request addPostValue:cityTextField.text forKey:@"city"];
    [request addPostValue:countryTextField.text forKey:@"country"];
    [request addPostValue:phoneTextField.text forKey:@"phone"];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        
    }
    [loading stopAnimating];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Order successfully !" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];    
}

- (BOOL)isTextFilled{
    if ((fullNameTextField.text == nil) ||[fullNameTextField.text isEqualToString:@""] || [streetTextField.text isEqualToString:@""] || (streetTextField.text == nil) || [cityTextField.text isEqualToString:@""] || (cityTextField.text == nil) || [countryTextField.text isEqualToString:@""] || (countryTextField.text == nil) || [phoneTextField.text isEqualToString:@""] || (phoneTextField.text == nil)) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
        return NO;
    }
    self.navigationItem.rightBarButtonItem.enabled = YES;
    return YES;
}

- (void)hideKeyboard{
    [streetTextField resignFirstResponder];
    [fullNameTextField resignFirstResponder];
    [countryTextField resignFirstResponder];
    [phoneTextField resignFirstResponder];
    [cityTextField resignFirstResponder];
}

#pragma mark Alert View Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == fullNameTextField) {
        [streetTextField becomeFirstResponder];
        return NO;
    }else if ([textField isEqual:streetTextField]){
        [cityTextField becomeFirstResponder];
        return NO;
    }else if ([textField isEqual:cityTextField]){
        [countryTextField becomeFirstResponder];
        return NO;
    }else if ([textField isEqual:countryTextField]){
        [phoneTextField becomeFirstResponder];
        return NO;
    }else if ([self isTextFilled]){
        [self didFinishOrder];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([self isTextFilled]) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}
                                                                                                                                                
#pragma mark Table View Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"Ship to";
    }
    return @"Payment method";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderCell"];
    CGRect frame = cell.frame;
    if ([indexPath section] == 0) {
        CGRect tempFrame = CGRectMake(frame.origin.x+15, frame.origin.y, frame.size.width-25, frame.size.height);
        switch ([indexPath row]) {
            case 0:{
                fullNameTextField = [[UITextField alloc]initWithFrame:tempFrame];
                fullNameTextField.placeholder = @"Full name";
                fullNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                fullNameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                fullNameTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                fullNameTextField.delegate = self;
                [cell addSubview:fullNameTextField];
            }
                break;
                
            case 1:{
                streetTextField = [[UITextField alloc]initWithFrame:tempFrame];
                streetTextField.placeholder = @"Street";
                streetTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                streetTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                streetTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                streetTextField.delegate = self;
                [cell addSubview:streetTextField];
            }
                break;
                
            case 2:{
                cityTextField = [[UITextField alloc]initWithFrame:tempFrame];
                cityTextField.placeholder = @"City";
                cityTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                cityTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                cityTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                cityTextField.delegate = self;
                [cell addSubview:cityTextField];
            }
                break;
                
            case 3:{
                countryTextField = [[UITextField alloc]initWithFrame:tempFrame];
                countryTextField.placeholder = @"Country";
                countryTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                countryTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                countryTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                countryTextField.delegate = self;
                [cell addSubview:countryTextField];
            }
                break;
                
            case 4:{
                phoneTextField = [[UITextField alloc]initWithFrame:tempFrame];
                phoneTextField.placeholder = @"Phone";
                phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
                phoneTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                phoneTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                phoneTextField.keyboardType = UIKeyboardTypePhonePad;
                phoneTextField.delegate = self;
                [cell addSubview:phoneTextField];
            }
                break;
                
            default:
                break;
        }
    }else{
        cell.textLabel.text = @"Pay later";
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    return cell;
}

#pragma mark Table View Delegates
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
@end
